import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Not, Repository } from 'typeorm';
import { Company } from '@app/models/company';

@Injectable()
export class CompanyService {
    constructor(
        @InjectRepository(Company)
        private companies: Repository<Company>,
    ) {}

    async getCompanies() {
        return this.companies.find({
            order: {
                id: "ASC"
            },
        });
    }

    getCompany(id: number): Promise<Company> {
        return this.companies.findOne({
            where: {
                id,
            },
        });
    }

    async add(dto: Company) {
        try {
            const companyInfo = await this.companies.findOne({
                where: { name: dto.name },
            });
            if (companyInfo) {
                throw new HttpException(
                    '同名公司已存在',
                    HttpStatus.BAD_REQUEST
                );
            }
            return this.companies.save(dto);
        } catch (error) {
            throw new HttpException(
                '数据库查询出错',
                HttpStatus.INTERNAL_SERVER_ERROR
            );
        }
    }

    async update(newData: Company) {
        const companyInfo = this.companies.findOne({
            where: { name: newData.name, id: Not(newData.id) },
        });
        if (await companyInfo) {
            throw new HttpException(
                '同名的其他公司已存在',
                HttpStatus.BAD_REQUEST
            );
        }
        await this.companies.update(newData.id, newData);
        return this.companies.findOne({
            where: {
                id: newData.id,
            },
        });
    }

    async del(id: number) {
        const company = this.companies.findOne({
            where: {
                id: id,
            },
        });
        return this.companies.remove(await company);
    }
}
